/** Description of TTDbAdapter.java 
 *
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 *
 */
package com.panther.awp.android.smoker.database;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;

public class TTDbAdapter extends AbstractDbAdapter {

	public TTDbAdapter(Context context) {
		super(context);
	}

	@Override
	public long create(ContentValues values) {
		return mDb.insert(TIMES_TRACK, null, values);
	}
	
	@Override
	public long update(long _id, ContentValues values) {
		return mDb.update(TIMES_TRACK, values, TT_PK_ID+"=" + _id, null);
	}
	
	@Override
	public long delete(long _id) {
		return mDb.delete(TIMES_TRACK, TT_PK_ID + "=" + _id, null);
	}
	
	@Override
	public Cursor fetchAll() {
		return mDb.query(TIMES_TRACK, null, null, null, null, null, null);
	}

	@Override
	public Cursor fetch(long _id) {
		return mDb.query(TIMES_TRACK, null, DT_PK_ID + "=" + _id, null, null, null, null);
	}
	
	@Override
	public Cursor fetchOldest() {
		return mDb.query(true, TIMES_TRACK, null, null, null, null, null, TT_DATETIME + " ASC", "1");
	}

	@Override
	public Cursor fetchLatest() {
		return mDb.query(true, TIMES_TRACK, null, null, null, null, null, TT_DATETIME + " DESC", "1");
	}
	
	public Cursor fetchInBetweenDate(Date afterThisDate, Date beforeThisDate) {
		String fromDateStr = DATE_FORMAT.format(afterThisDate);
		String toDateStr = DATE_FORMAT.format(beforeThisDate);
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		queryBuilder.setTables(TIMES_TRACK);
		return queryBuilder.query(mDb, null, TT_DATETIME + " >= '"+ fromDateStr +"' AND "+ TT_DATETIME + " < '"+ toDateStr +"'", null, null, null, null);
	}
	
	public Cursor fetchLatestSmokeEntry() {
		return mDb.query(true, TIMES_TRACK, null, null, null, null, null, TT_DATETIME + " DESC", "1");
	}
	
	public Cursor fetchLatestSmokeEntry(Long brandId) {
		return mDb.query(true, TIMES_TRACK, null, TT_BRAND_ID + " = '" + brandId + "'", null, null, null, TT_DATETIME + " DESC", "1");
	}

	public Cursor fetchOldestSmokeEntry() {
		return mDb.query(true, TIMES_TRACK, null, null, null, null, null, TT_DATETIME + " ASC", "1");
	}
	
	public Cursor fetchEntryOlderThan(Date date) {
		String dateStr = DATE_FORMAT.format(date);
		return mDb.query(TIMES_TRACK, null, TT_DATETIME + " <= '" + dateStr + "'", null, null, null, TT_DATETIME + " ASC");
	}

}
